How to Access Enum Names and Values in Python
Enums (enumerations) in Python provide a way to define named constants, improving code readability and maintainability.
This guide explores how to access enum names and values, retrieve names by value, and get lists of enum members, enhancing your ability to work with enums effectively.
Accessing Enum Names and Values
Accessing by Name
Use dot notation on the enum class to access members by name, then the .name
and .value
properties to get their name and value:
from enum import Enum
class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
print(Sizes.SMALL.name) # Output: SMALL
print(Sizes.SMALL.value) # Output: 1
Accessing by Value
If you only have the value and need the name, use the enum class call with the value, and access the .name
property:
print(Sizes(1).name) # Output: SMALL
print(Sizes(2).name) # Output: MEDIUM
- The
Sizes(value)
syntax returns the appropriate enum member, if one exists for that value.
Accessing with Square Brackets
You can also access enum members by name as strings using square bracket notation:
size_name = 'LARGE'
print(Sizes[size_name].name) # Output: LARGE
print(Sizes[size_name].value) # Output: 3
- This approach is especially useful if the name is obtained dynamically (e.g., from user input or a configuration file).
Getting All Enum Values or Names
To get lists of all values or names in an enum, use list comprehensions:
values = [member.value for member in Sizes]
print(values) # Output: [1, 2, 3]
names = [member.name for member in Sizes]
print(names) # Output: ['SMALL', 'MEDIUM', 'LARGE']
name_value_pairs = [(member.name, member.value) for member in Sizes]
print(name_value_pairs) # Output: [('SMALL', 1), ('MEDIUM', 2), ('LARGE', 3)]
Iterating Over Enums
You can loop directly over an enum's members:
from enum import Enum
class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
for size in Sizes:
print(size) # Output: Sizes.SMALL, Sizes.MEDIUM, Sizes.LARGE
print(size.name, size.value) # Output: SMALL 1, MEDIUM 2, LARGE 3
Checking for Membership with in
Use the in
operator to check if a value exists within an enum:
values = [member.value for member in Sizes]
if 2 in values:
print('2 is in values') # Output: 2 is in values